import sys

import pyvirtualcam
import cv2

# 打开视频文件或摄像头
cap = cv2.VideoCapture(0)  # 0 表示本地摄像头

if not cap.isOpened():
    print('未发现摄像头')
    sys.exit(0)

# 获取视频分辨率和帧率
video_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
video_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
video_fps = int(cap.get(cv2.CAP_PROP_FPS))

with pyvirtualcam.Camera(width=video_width, height=video_height, fps=video_fps) as cam:
    print(f'Using virtual camera: {cam.device}')
    while True:
        ret, frame = cap.read()
        if not ret:
            print("视频播放结束，重新开始播放")
            cap.set(cv2.CAP_PROP_POS_FRAMES, 0)  # 重置帧位置到开头
            continue  # 跳过当前循环，重新读取帧
        # 将图像发送到虚拟摄像头
        cam.send(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
        cam.sleep_until_next_frame()
